import {createRouter, createWebHistory} from 'vue-router'
import ModelView from '../views/left/index.vue'
import PanelView from '../views/PanelView.vue'
import DOMView from '../views/DOMView.vue'
import Login from '../views/Login.vue'
import Home from '../views/Home.vue'

const routes = [
    {path: '/model', component: ModelView},
    {path: '/panel', component: PanelView},
    {path: '/dom', component: DOMView},
    {path: '/', component: Login},
    {path: '/Login', component: Login},
    {
        path: '/home',
        name: 'Home',
        component: Home,
        meta: {requiresAuth: true}, // 标记此路由需要认证
    },
]

const router = createRouter({
    history: createWebHistory(),
    routes
})
// 路由守卫：检查用户是否已登录
router.beforeEach((to, _from, next) => {
    const isAuthenticated = !!localStorage.getItem('authToken'); // 检查是否有 token
    const requiresAuth = to.matched.some(record => record.meta.requiresAuth);

    if (requiresAuth && !isAuthenticated) {
        // 如果目标路由需要认证且用户未登录，重定向到登录页面
        next({path: '/'});
    } else if (to.path === '/' && isAuthenticated) {
        // 如果用户已登录且访问的是登录页面，重定向到内容页
        next({path: '/home'});
    } else {
        // 否则继续导航
        next();
    }
});
export default router;